<?php

namespace cf\api\gallery;

require_once dirname(__FILE__).'/../db.php';

function getAlbums($parentId=null, &$items=array(), $showHidden=false)
{
	$parentId = getAlbumID($parentId);
	
	$q = null;
	\cf\createStaticQuery($q,"
		SELECT id, IFNULL(code,id) AS code, parent_id, name, image, short_descr, descr, hidden, sort_order, tag_title, tag_meta_keywords, tag_meta_descr
		FROM cf_gallery_albums
		WHERE (parent_id=:parentId OR (:parentId IS NULL AND parent_id IS NULL))
			". ($showHidden ? '' : 'AND (hidden IS NULL OR hidden=0)') . "
		ORDER BY sort_order ASC
	");
	$albums = \cf\query2arrays($q,array('parentId'=>$parentId));
	foreach ($albums as $album) {
		$album['children'] = array();
		getAlbums($album['id'], $album['children'], $showHidden);
		$items[] = $album;
	}
	return $items;
}

function getAlbumID($code)
{
	if (!$code) {		//root album
		return null;
	}
	if (is_numeric($code)) {
		return (int)$code;
	}
	return \cf\query2var("SELECT id FROM cf_gallery_albums WHERE code=:code",array('code'=>substr($code, strrpos($code,'/')!==false?strrpos($code,'/')+1:0)));
}

function getAlbum($id)
{
	return \cf\query2array("
		SELECT * FROM cf_gallery_albums WHERE id=:id",
		array('id'=>getAlbumID($id))
	);
}

function getImage($id)
{
	$image = \cf\query2array("
		SELECT * FROM cf_gallery_images WHERE id=:id",
		array('id'=>$id)
	);
	
	$image['albums'] = \cf\query2arrays("
		SELECT cf_gallery_albums.id, IFNULL(cf_gallery_albums.code,cf_gallery_albums.id) AS code, name, image, hidden 
		FROM cf_gallery_image_in_album 
		INNER JOIN cf_gallery_albums ON album_id=cf_gallery_albums.id
		WHERE image_id=:id",
		array('id'=>$id)
	);
	
	return $image;
}

function getImages($albumId, $showHidden=false)
{
	$albumId = getAlbumID($albumId);
	
	return \cf\query2arrays("
		SELECT cf_gallery_images.id AS id, IFNULL(code,cf_gallery_images.id) AS code, name, image, short_descr, hidden, url
		FROM cf_gallery_images
		INNER JOIN cf_gallery_image_in_album ON cf_gallery_images.id=cf_gallery_image_in_album.image_id
		WHERE cf_gallery_image_in_album.album_id=:aid
		ORDER BY sort_order",
		array('aid'=>$albumId)
	);
}